<?php
/**
 * Copyrigh () 2017 湖南魔工坊科技有限公司 版权所有
 * 网址：http://www.mogo.club
 * 项目名称：环球世界交易平台
 * 文件名称：Finance.php
 * 时间：2017年8月25日
 * 作者：
 */

namespace app\world\home;


use app\world\home\Common;
use app\world\model\Configs;
use app\world\model\Order as OrderModel;
use app\world\model\NewsUser;
use app\world\model\User;
use app\world\model\Mortgage;

class Order extends Common
{

    /**
     * 我的资产
     * @author 
     */
    public function index()
    {
        $OrderModel = new OrderModel();


        $map['world_order.user_id'] = session('home_user')['id'];
        $map['world_order.type'] = ['in', [1, 3]];
        $map['world_order.surplus_sum'] = ['>', 0];
        $data = $OrderModel->get_list($map,'id desc','',1);
        if (!$_SESSION['is_language']) {
            foreach ($data as $k => &$v) {
                $v->goods_name = str_replace('比克', 'bike', $v->goods_name);
            }
        }
//        echo json_encode($data);die;

        $this->assign([
            'data' => $data
        ]);
        return $this->fetch();
    }

    /**
     * 页面ajax请求
     * @author 
     */
    public function ajax()
    {
        $id = input('id');
        if (!$id) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $OrderModel = new OrderModel();
        $con = new Configs();
        $con_data = $con->get_find('purchase_fee,sell_fee');
        $order = $OrderModel->get_find(['world_order.id' => $id, 'world_order.user_id' => session('home_user')['id']]);
        if (!$order) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $data['order'] = $order;
        $data['con']['purchase_fee'] = $con_data->purchase_fee;
        $data['con']['sell_fee'] = $con_data->sell_fee;
        return ['code' => 1, 'msg' => '', 'content' => $data];
    }


//    /**
//     * 兑出資產
//     * @author 
//     */
//    public function sell()
//    {
//        if ($this->request->post()) {
//            $OrderModel = new OrderModel();
//            $NewsUser = new NewsUser();
//            $info = input();
//            $order = $OrderModel->get_find(['world_order.id' => $info['id'], 'world_order.user_id' => session('home_user')['id']]);
//            $order_data = $order->toArray();
//            if (!$order) $this->error('資產不存在');
//            if ($order->surplus_sum < $info['sum']) $this->error('資產数量不足');
//            $data['order_id'] = $order_data['id'];
//            $data['type'] = 2;
//            $data['pid'] = $order_data['pid'];
//            $data['user_id'] = $order_data['user_id'];
//            $data['goods_id'] = $order_data['goods_id'];
//            $data['money'] = $order_data['money'];
//            $data['money2'] = $order_data['goods_money'];
//            $data['sum'] = $info['sum'];
//            $data['actual_sum'] = $info['sum'];
//            $data['surplus_sum'] = $info['sum'];
//            $OrderModel->add_order($data);
//            $order->surplus_sum -= $info['sum'];
//            $order->save();
//            $NewsUser->title = '兑出資產';
//            $NewsUser->user_id = $order_data['user_id'];
//            $NewsUser->content = '您兑出的資產正在匹配交易会员,请前往資產兑出记录查看详情';
//            $NewsUser->save();
//            $this->success('操作成功');
//        }
//        echo '非法操作';
//    }

    /**
     * 兑出資產
     * @author 
     */
    public function sell()
    {
        if ($this->request->post()) {
            $OrderModel = new OrderModel();
            $NewsUser = new NewsUser();
            $info = input();
            $order = $OrderModel->get_find(['world_order.id' => $info['id'], 'world_order.type' => ['in', [1, 3]], 'world_order.user_id' => session('home_user')['id']]);
            if (!$order) return ['code' => 0, 'msg' => '資產不存在', 'msg1' => 'Commodity does not exist', 'content' => ''];
            $order_data = $order->toArray();
            if ($order->surplus_sum < $info['sum']) return ['code' => 0, 'msg' => '資產數量不足', 'msg1' => 'Insufficient commodity quantity', 'content' => ''];

            //手续费
//            $user = User::get($order->user_id);
            $con = new Configs();
            $con_data = $con->get_find('purchase_fee,sell_fee');
//            if ($user->money1 < $info['sum'] * $order_data['goods_money'] * $con_data->sell_fee) {
//                return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low', 'content' => ''];
//            }

            $data['sell_fee'] = $con_data->sell_fee;
            $data['order_id'] = $order_data['id'];
            $data['type'] = 2;
            $data['pid'] = $order_data['pid'];
            $data['user_id'] = $order_data['user_id'];
            $data['goods_id'] = $order_data['goods_id'];
            $data['money'] = $order_data['money'];
            $data['money2'] = $order_data['goods_money'];
            $data['sum'] = $info['sum'];
            $data['buy_type']=$order_data['buy_type'];
            $data['actual_sum'] = $info['sum'];
            $data['surplus_sum'] = $info['sum'];
            $OrderModel->add_order($data);
            $order->surplus_sum -= $info['sum'];
            $order->save();
            if(!empty($data['buy_type'])&&$data['buy_type']==2){//做空消息提示修改
                $msg='您的做空合約已申請，請等待審核';
                $msg1='Your short contract has been applied, please wait for the review';
//                    $NewsUser->content = '您的做空合約資產已經生效，請等待審核。Your short contract assets have entered into force. Please wait for the audit';
            }else{
                $msg= '您賣出的資產正在匹配資產買家';
                $msg1= 'The assets you sell are matching the asset buyers';
//                    $NewsUser->content = '您購買的資產正在匹配資產賣家。The assets you buy are matching the asset seller';
            }
            $NewsUser->title = '資產消息。Asset message';
            $NewsUser->user_id = $order_data['user_id'];
//            $NewsUser->content = '您賣出的資產正在匹配資產買家。The assets you sell are matching the asset buyers  ';
            $NewsUser->content =$msg.'。'.$msg1;
            $NewsUser->save();
            //return ['code' => 0, 'msg' => '您賣出的資產正在匹配資產買家', 'msg1' => 'The assets you sell are matching the asset buyers', 'content' => ''];
            return ['code' => 0, 'msg' => $msg, 'msg1' => $msg1, 'content' => ''];
        }
        return ['code' => 0, 'msg' => '非法操作', 'msg1' => 'Illegal operation', 'content' => ''];
    }

    /**
     * 兑出记录
     * @author 
     */
    public function selllist()
    {
        $OrderModel = new OrderModel();
        $map['world_order.user_id'] = session('home_user')['id'];
        $map['world_order.type'] = 2;

        $order = 'world_order.status,id desc';
        $data = $OrderModel->get_list($map, $order, 15);

        if (!$_SESSION['is_language']) {
            foreach ($data as $k => &$v) {
                $v->goods_name = str_replace('比克', 'bike', $v->goods_name);
            }
        }

        $this->assign([
            'data' => $data
        ]);
        return $this->fetch();
    }

    /**
     * 兑出记录
     * @author
     */
    public function selllist2()
    {
        $OrderModel = new OrderModel();
        $map['world_order.user_id'] = session('home_user')['id'];
        $map['world_order.type'] = 2;

        $order = 'world_order.status,id desc';
        $data = $OrderModel->get_list($map, $order, 15);

        if (!$_SESSION['is_language']) {
            foreach ($data as $k => &$v) {
                $v->goods_name = str_replace('比克', 'bike', $v->goods_name);
            }
        }

        $this->assign([
            'data' => $data
        ]);
        return $this->fetch();
    }

    /**
     * 取消兑出
     * @author 
     */
    public function cancel()
    {
        $id = input('id');
        if (!$id) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters', 'content' => ''];
        $OrderModel = new OrderModel();
        $order2 = $OrderModel->get_find(['world_order.id' => $id, 'world_order.type' => 2, 'world_order.user_id' => session('home_user')['id']]);
        if (!$order2) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '記錄不存在' : 'Record does not exist', 'content' => ''];
        //手续费
//        $user = User::get($order2->user_id);
//        $user->money1 += $order2->actual_sum * $order2->money2 * $order2->sell_fee;
//        $user->save();
        $order2->status = 3;
        $order2->sell_fee = 0;
        $order2->save();
        $order1 = $OrderModel->get_find(['world_order.id' => $order2->order_id]);
        $order1->surplus_sum += $order2->sum;
        $order1->save();
        return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation', 'content' => ''];
    }


    /**
     * 資產转出
     * @author 
     */
    public function turnout()
    {
        die;
        $id = input('id');
        if (!$id) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $OrderModel = new OrderModel();
        $order = $OrderModel->get_find(['world_order.id' => $id, 'world_order.type' => 1, 'world_order.user_id' => session('home_user')['id']]);
        if (!$order) $this->error(@$_SESSION['is_language'] ? '記錄不存在' : 'Record does not exist');
        if ($this->request->post()) {
            $User = new User();
            $data = input();
            $pwd = session('home_password');
            $password = 'password' . $pwd;
            $user_data = $User->get_find(['id' => session('home_user')['id']]);
            if ($user_data->$password != $User->add_password($data['password'])) $this->error(@$_SESSION['is_language'] ? '密碼錯誤' : 'Password error');
            if ($data['username'] == session('home_user')['username']) $this->error(@$_SESSION['is_language'] ? '轉出用戶不能是自己' : 'Cant be myself');
            $p_user = $User->get_find(['username' => $data['username']]);
            $pid = $User->get_pid($p_user->id);
            if (!$p_user) $this->error('轉出用戶不存在');
            if ($p_user->group_id == 2 || $pid != $order->pid) $this->error(@$_SESSION['is_language'] ? '該用戶不符合規則' : 'Non conformity rule');
            if (!is_numeric($data['sum']) || $data['sum'] < 0) $this->error(@$_SESSION['is_language'] ? '轉出數量不正確' : 'Incorrect number of rolls out');
            if ($order->surplus_sum < $data['sum']) $this->error(@$_SESSION['is_language'] ? '資產數量不足' : 'Lack of assets');
            $OrderModel->pid = $order->pid;
            $OrderModel->transfer_id = $order->user_id;
            $OrderModel->user_id = $p_user->id;
            $OrderModel->goods_id = $order->goods_id;
            $OrderModel->sum = $data['sum'];
            $OrderModel->actual_sum = $data['sum'];
            $OrderModel->surplus_sum = $data['sum'];
            $OrderModel->is_transfer = 1;
            $OrderModel->status = 1;
            $OrderModel->order_id = $order->id;
            $OrderModel->save();
            $order->surplus_sum -= $data['sum'];
            $order->save();
            $NewsUser = new NewsUser();
            $NewsUser->title = '資產交易。Asset transaction';
            $NewsUser->content = '有交易用戶給您轉入資產,請前往我的資產-資產交易記錄查看。There is a transaction user to transfer your assets, please go to my asset asset transaction record view';
            $NewsUser->user_id = $p_user->id;
            $NewsUser->save();
            $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', '', '', 1);
        }
        $this->assign([
            'order' => $order,
        ]);
        return $this->fetch();
    }


    /**
     * 資產互转记录
     * @author 
     */
    public function record()
    {
        if (input('username')) {
            $user = User::get(['username' => input('username')]);
            if (!$user) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        }
        isset($user) ? $map['user_id'] = $user->id : $map['user_id'] = session('home_user')['id'];

        $OrderModel = new OrderModel();
        input('type') ? $type = input('type') : $type = 1;
        $data = $OrderModel->get_record($map['user_id'], $type, '', 15);
        $this->assign([
            'data' => $data,
            'type' => $type,
            'user' => @$user
        ]);
        return $this->fetch();
    }


    /**
     * 資產抵押人列表
     * @author 
     */
    public function lists()
    {
        $Order = new OrderModel();
        $order_id = input('order_id');
        if (!$order_id) $this->error(@$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error');
        $user_id = session('home_user')['id'];
        $order = $Order->get_find(['world_order.id' => $order_id, 'world_order.user_id' => $user_id, 'type' => 1, 'surplus_sum' => ['gt', 0]]);
        if (!$order) $this->error(@$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error');
        $Con = new Configs();
        $configs = $Con->get_find();
        if ($this->request->post()) {
            $data = input();
            //$data['sum'] = intval($data['sum']);
            if (!is_numeric($data['money']) || is_numeric($data['money']) < 0) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error', 'content' => ''];
            //if (is_numeric($data['sum']) < 0) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error', 'content' => ''];
            if ($data['day'] < 1) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '抵押天數至少大於1天' : 'The number of mortgages is at least 1 days', 'content' => ''];
            //if ($order->surplus_sum < $data['sum']) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產數量不足' : 'Insufficient quantity', 'content' => ''];
            $data['sum'] = $order->surplus_sum;
            if ($order->goods_money * $data['sum'] * $configs->mortgage_top < $data['money']) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '貸款不能高於資產價值的' . ($configs->mortgage_top * 100) . '%' : 'A loan cannot be higher than the value of the asset', 'content' => ''];
            $User = new User();
            $list = $User->get_mortgage($user_id, $data['money']);
            $_SESSION['mortgage'] = $data;
            return ['code' => 1, 'msg' => '', 'content' => $list];
        }
        $info['sum_money'] = $order->surplus_sum * $order->goods_money;
        $info['mortgage_top_money'] = $info['sum_money'] * $configs->mortgage_top;
        $order_id = input('order_id');
        $this->assign([
            'order_id' => $order_id,
            'info' => $info
        ]);
        return $this->fetch();
    }

    /**
     * 資產抵押人列表-ajax
     * @author 
     */
    public function lists_ajax()
    {
        if ($this->request->post()) {
            $data = $_SESSION['mortgage'];
            $data['mortgage_id'] = input('mortgage_id');
            $data['mortgage'] = input('mortgage');
            $data['sum'] = intval($data['sum']);
            if (!is_numeric($data['money']) || is_numeric($data['money']) < 0) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error', 'content' => ''];
            if (is_numeric($data['sum']) < 0) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error', 'content' => ''];
            if ($data['day'] < 1) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '抵押天數至少大於1天' : 'The number of mortgages is at least 1 days', 'content' => ''];
            $order_id = $data['order_id'];
            $Order = new OrderModel();
            $user_id = session('home_user')['id'];
            $order = $Order->get_find(['world_order.id' => $order_id, 'world_order.user_id' => $user_id, 'type' => 1, 'surplus_sum' => ['gt', 0]]);
            if (!$order) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '參數錯誤' : 'Parameter error', 'content' => ''];
            if ($order->surplus_sum < $data['sum']) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產數量不足' : 'Insufficient quantity', 'content' => ''];
            $Con = new Configs();
            $configs = $Con->get_find();
            if ($order->goods_money * $data['sum'] * $configs->mortgage_top < $data['money']) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '貸款不能高於資產價值的' . ($configs->mortgage_top * 100) . '%' : 'A loan cannot be higher than the value of the asset', 'content' => ''];
            $info = [
                'user_id' => $user_id,
                'mortgage_id' => $data['mortgage_id'],
                'order_id' => $order->id,
                'sum' => $data['sum'],
                'goods_money' => $order->goods_money,
                'day' => $data['day'],
                'mortgage' => $data['mortgage'],
                'money' => $data['money'],
            ];
            $Mortgage = new Mortgage();
            $Mortgage->add($info);
            //减资产
            $order->surplus_sum -= $data['sum'];
            $order->save();
            //用户消息
            $NewsUser = new NewsUser();
            $NewsUser->title = '資產抵押。Asset mortgage';
            $NewsUser->content = '您的抵押申請正在審核。Your mortgage is being audited';
            $NewsUser->user_id = $user_id;
            $NewsUser->save();
            $User = new User();
            $on_mortgage = $User->get_no_mortgage($user_id, $data['money']);
            if ($on_mortgage) {
                foreach ($on_mortgage as $item) {
                    $infos = array();
                    $infos = [
                        'user_id' => $user_id,
                        'mortgage_id' => $item['id'],
                        'order_id' => $order->id,
                        'sum' => $data['sum'],
                        'goods_money' => $order->goods_money,
                        'day' => $data['day'],
                        'mortgage' => $data['mortgage'],
                        'money' => $data['money'],
                        'status' => 6,
                    ];
                    Mortgage::create($infos);
                }
            }
            return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation', 'content' => ''];
        }
    }


    /**
     * 抵押记录
     * @author 
     */
    public function mortgage()
    {
        $user_id = session('home_user')['id'];
        $Mortgage = new Mortgage();
        $list = $Mortgage->get_all(['mortgage.user_id' => $user_id, 'mortgage.status' => ['NEQ', 6]], 'create_time desc');
        if ($this->request->post()) {
            $data = input();
            $mortgage = $Mortgage->get_all(['mortgage.id' => $data['id']]);
            if ($data['status'] == 4) {  //取消抵押
                if ($mortgage[0]->status != 0) {
                    return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '操作失敗' : 'Operation failed', 'content' => ''];
                }
                $mortgage[0]->status = $data['status'];
                $mortgage[0]->save();
                $order = OrderModel::get($mortgage[0]->order_id);
                $order->surplus_sum += $mortgage[0]->sum;
                $order->save();
                $NewsUser = new NewsUser();
                $NewsUser->title = '資產抵押。Asset mortgage';
                $NewsUser->content = '您的抵押已取消。Your mortgage has been cancelled';
                $NewsUser->user_id = $user_id;
                $NewsUser->save();
                return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation', 'content' => ''];
            }


            if ($data['status'] == 2) { //赎回
                if ($mortgage[0]->status != 1) {
                    return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作失敗' : 'Operation failed', 'content' => ''];
                }
                $time = floor((time() - $mortgage[0]->time) / 86400);
                $money = ($time + 1) * $mortgage[0]->mortgage * $mortgage[0]->money + $mortgage[0]->money;
                if ($mortgage[0]->money1 < $money) return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low', 'content' => ''];

                $user = User::get($user_id);
                $user->money1 -= $money;
                $user->save();

                $mortgage_user = User::get($mortgage[0]->mortgage_id);
                $mortgage_user->money1 += $money;
                $mortgage_user->save();


                $chang = '贖回抵押給‘'.$mortgage_user->username.'’的資產 Redemption of assets';
                User::money_change($user->id, 0, $money, $chang);
                $chang = '用戶‘'.$user->username.'’贖回抵押資產 Redemption of assets';
                User::money_change($mortgage_user->id, 1, $money, '資產贖回 Redemption of assets');

                $mortgage[0]->status = $data['status'];
                $mortgage[0]->time_end = time();
                $mortgage[0]->save();

                $order = OrderModel::get($mortgage[0]->order_id);
                $order->surplus_sum = $mortgage[0]->sum;
                $order->save();
                $NewsUser = new NewsUser();
                $NewsUser->title = '資產抵押。Asset mortgage';
                $NewsUser->content = '您的抵押已贖回。Your mortgage has been redeemed';
                $NewsUser->user_id = $user_id;
                $NewsUser->save();
                return ['code' => 1, 'msg' => @$_SESSION['is_language'] ? '操作成功' : 'Successful operation', 'content' => ''];
            }
        }

        foreach ($list as &$value) {
            $ruls = $Mortgage->mortgage_ruls($value->id);
            $value->past_time = $ruls['past_time'];
            $value->redeem_money = $ruls['redeem_money'];
        }


        $this->assign([
            'list' => $list
        ]);
        return $this->fetch();
    }


}